<?php

class str_SmugMug {

	const apiKey = 'tpwKjD9tyr42symMnjSvhTGPyQpNpbHE';
	const apiSecret = '3b7be1219eae97ec77bf242d46bbb12d';
	const apiAppName = 'SmugPlug App/1.0 (http://sotomajor.org.ua)';
	const apiVersion = '1.2.2';
	
	private $_smugLogin = null;
	private $_phpSmug = null;
	private $_success = true;
	private $_albumList = null;
	
	public function __construct($smugLogin = '') {
		$this->_smugLogin = $smugLogin;
		$this->_phpSmug = new phpSmug("APIKey=" . self::apiKey, 
								"AppName=" . self::apiAppName, 
								"APIVer=" . self::apiVersion);
        $this->_success = is_array($this->_phpSmug->login());
	}
	
	public function getSuccess() {
		return (bool)$this->_success;
	}
	
	/**
	 * Returns list of albums
	 */
	public function getAlbumList() {
		if ($this->_albumList === null) {
			$albumDataSets = $this->_phpSmug->albums_get('NickName=' . $this->_smugLogin);
            foreach ($albumDataSets as $albumDataSet) {
                $this->_albumList[] = new str_SmugMugAlbum($albumDataSet, $this->_phpSmug);
            }
		}

		return $this->_albumList;
	}
	
	public function getRandomAlbum() {
		$albumCount = count($this->getAlbumList());
        $albumList = $this->getAlbumList();
		if (!is_array($albumList) || $albumCount == 0) {
			return null;
		}
		
		return $albumList[rand(0, $albumCount - 1)];
	}
    
    /**
     * Returns album object by id and key
     * @param integer id
     * @param integer key
     * @return str_SmugMugAlbum or null
     */
    public function getAlbumByIdAndKey($id, $key) {
        try {
            $albumData = $this->getPhpSmug()->albums_getInfo('AlbumID=' . $id, 'AlbumKey=' . $key);
        } catch (Exception $e) {
            return null;
        }

        return new str_SmugMugAlbum($albumData, $this->getPhpSmug());
        
    }
    
    /**
     * Returns image object by id and key
     * @param integer $id
     * @param string $key
     * @return str_SmugMugImage or null
     */
    public function getImageByIdAndKey($id, $key) {
        try {
            $imageData = $this->getPhpSmug()->images_getInfo('ImageID=' . $id, 'ImageKey=' . $key);
        } catch (Exception $e) {
            return null;
        }

        $album = $this->getAlbumByIdAndKey($imageData['Album']['id'], $imageData['Album']['Key']);
        return new str_SmugMugImage($imageData, $this->getPhpSmug(), $album);
    }
    
    public function getPhpSmug() {
        return $this->_phpSmug;
    }

}